const DOWNLOADBINNING_ID = "downloadbinning@downloadbinning.net";

var dbUninstallObserver = {
  _uninstall : false,
  
  observe : function(subject, topic, data) {
    if (topic == "em-action-requested") {
     subject.QueryInterface(Components.interfaces.nsIUpdateItem);

     if (subject.id == DOWNLOADBINNING_ID) {
       if (data == "item-uninstalled") {
         this._uninstall = true;
       } else if (data == "item-cancel-action") {
         this._uninstall = false;
       }
     }
    } else if (topic == "quit-application-granted") {
      if (this._uninstall) {
        var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
        pref.deleteBranch("extensions.downloadbinning");
      }     
      this.unregister();
    }
  },
      
   // Registers the observer to check for extension update and application exit
   register: function() {
      var observerService = 
         Components.classes["@mozilla.org/observer-service;1"].
            getService(Components.interfaces.nsIObserverService);
 
      observerService.addObserver(this, "em-action-requested", false);
      observerService.addObserver(this, "quit-application-granted", false);
   },

   // Unregisters the observer.
   unregister: function() {
      var observerService = 
        Components.classes["@mozilla.org/observer-service;1"].
           getService(Components.interfaces.nsIObserverService);
  
      observerService.removeObserver(this, "em-action-requested");
      observerService.removeObserver(this, "quit-application-granted");
   }
};

function bd_onLoad(event) {
  try {
    dbUninstallObserver.register();

  } catch (e) {
    throw e;
  }
}

window.addEventListener("load", bd_onLoad, false);
 
